package com.dcy.znoa.controller.attendance;

import com.aliyuncs.exceptions.ClientException;
import com.baomidou.mybatisplus.plugins.Page;
import com.dcy.znoa.common.annotation.AuthenticationAPI;
import com.dcy.znoa.common.controller.BaseController;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.DateTimeUtil;
import com.dcy.znoa.common.util.StringPy;
import com.dcy.znoa.common.util.excel.ExcelOutput;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.attendance.model.apply.*;
import com.dcy.znoa.domain.attendance.Apply;
import com.dcy.znoa.service.attendance.ApplyService;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.*;

import static com.dcy.znoa.common.util.pojo.JsonCommon.SUCCESS_CODE;

/**
 * 员工申请表，含状态
 * @author pengyu
 */
@Controller
@RequestMapping("apply")
public class ApplyController extends BaseController {

    @Autowired
    ApplyService applyService;

    // 申请列表，通用接口,分页：申请类型 1 请假 2 出差 3 外勤 9 申述
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryList")
    public JsonForList queryList(SelectApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
//        List list = applyService.selectListMapper(model);
//        return new JsonForList(list);
        return applyService.selectList(model);
    }

    // 申请列表，通用接口,分页 导出
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/export")
    public JsonCommon export(@Valid SelectApplyModel model, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
//        return applyService.selectList(model);
        if (bindingResult.hasErrors()) {
            return new JsonCommon("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List<Map<String, Object>> recordList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();//list转map
//        Page page = new Page(model.getPageNum(), model.getPageSize());

        JsonForList jsonForList = applyService.selectList(model);
        List<Apply> list = jsonForList.getData();
        for (Apply apply :list) {
            recordList.add(Apply.toMap(apply));
        }
        String keys[] = {"depName", "operName", "phoneNo", "type_str", "applyTime", "address", "startTime", "endTime", "diff", "receiveOperName", "isAudit", "auditTime"};//map中的key
        String columnNames[] = {"部门", "姓名", "联系方式", "申请类型", "申请时间", "地点", "开始时间", "结束时间", "时长（小时）", "审批人", "审批状态","审批时间"};//列名
        ExcelOutput.ExcelOutput(request, response, recordList, keys, columnNames, "申请汇总");
        return new JsonCommon(SUCCESS_CODE);
    }
    // 查询申述列表，通用接口,分页
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryReasonList")
    public JsonForList queryReasonList(@Valid SelectApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
//        List list = applyService.queryReasonList(model);
//        return new JsonForList(list);
        return applyService.queryReasonList(model);
    }
    // 申述列表，通用接口,分页 导出
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/exportReason")
    public JsonCommon exportReason(@Valid SelectApplyModel model, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, IOException {
//        return applyService.selectList(model);
        if (bindingResult.hasErrors()) {
            return new JsonCommon("404", bindingResult.getFieldError().getDefaultMessage());
        }
        List<Map<String, Object>> recordList = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();//list转map
//        Page page = new Page(model.getPageNum(), model.getPageSize());

        JsonForList jsonForList = applyService.queryReasonList(model);
        List<Apply> list = jsonForList.getData();
        for (Apply apply :list) {
            recordList.add(Apply.toMap(apply));
        }
        String keys[] = {"depName", "operName", "phoneNo", "recordType","recordTime", "timeStatus", "address", "addStatus", "appTime", "receiveOperName", "isAudit", "auditTime"};//map中的key
        String columnNames[] = {"部门", "申述人", "联系方式", "班次",       "打卡时间", "时间异常情况", "打卡地点",    "地点异常情况", "申述时间", "审批人", "审批状态","审批时间"};//列名
        ExcelOutput.ExcelOutput(request, response, recordList, keys, columnNames, "申述汇总");
        return new JsonCommon(SUCCESS_CODE);
    }
    // 查看申请详情  查询图片列表、审核人姓名和头像url
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/queryDetail")
    public JsonForList queryDetail(Long applyId) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
        if(applyId==null){
            return  new JsonForList("404","申请id不能为空");
        }
        List list = applyService.queryDetail(applyId);
        return new JsonForList(list);
    }

    //APP  申请新增：申请类型 1 请假 2 出差 3 外勤 9 申述
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/add")
    public JsonCommon add(@Valid AddApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException, ClientException {
        if(StringUtils.isNotBlank(model.getRemoteFileName())){
            model.setRemoteFileName(StringPy.trim(model.getRemoteFileName()));
        }
        model.setCompId(getCurrentUser().getCompId());
        //时间格式的转换
//        String startTimeStr = model.getStartTimeStr();
//        String endTimeStr = model.getEndTimeStr();
//        Date startTime = DateTimeUtil.getHMSDate(startTimeStr);
//        Date endTime = DateTimeUtil.getHMSDate(endTimeStr);
//        model.setStartTime(startTime);
//        model.setEndTime(endTime);
        applyService.add(model);
        return new JsonCommon(SUCCESS_CODE);
    }

    //APP  申请撤销：申请类型 1 请假 2 出差 3 外勤 9 申述 已经同意的不能撤销
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/revoke")
    public JsonCommon revoke(@Valid RevokeApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Integer result = applyService.revoke(model);
        return new JsonCommon(SUCCESS_CODE);
    }

    //APP  申请审核：申请类型 1 请假 2 出差 3 外勤 9 申述  已经撤销的不应该被看到
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/audit")
    public JsonCommon audit(@Valid AuditApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException, ParseException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        Integer result = applyService.audit(model);
        return new JsonCommon(SUCCESS_CODE);
    }

    //APP  申请审核：申请类型 1 请假 2 出差 3 外勤 9 申述  已经撤销的不应该被看到
    @AuthenticationAPI
    @ResponseBody
    @RequestMapping("/selectSendAndReceiveNumByOperId")
    public JsonCommon selectSendAndReceiveNumByOperId(@Valid SendApplyModel model, BindingResult bindingResult) throws BusinessException, InvocationTargetException, IllegalAccessException {
        if (bindingResult.hasErrors()){
            return  new JsonCommon("404",bindingResult.getFieldError().getDefaultMessage());
        }
        SelectApplyNum selectApplyNum = applyService.selectSendAndReceiveNumByOperId(model);
        return new JsonCommon(selectApplyNum);
    }

}
